package com.bsj.power.job.web.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.fastjson.JSON;
import com.bsj.power.common.annotation.Log;
import com.bsj.power.common.config.cached.RedisCached;
import com.bsj.power.common.config.exception.ApiException;
import com.bsj.power.common.config.global.JsonResult;
import com.bsj.power.common.config.global.JsonResultEnum;
import com.bsj.power.common.config.redis.RedisConstant;
import com.bsj.power.common.constant.NumericalConstants;
import com.bsj.power.common.def.dto.PageDTO;
import com.bsj.power.common.def.dto.alarmReport.AlarmReportSearchDTO;
import com.bsj.power.common.def.dto.job.JobDTO;
import com.bsj.power.common.def.dto.job.JobSearchDTO;
import com.bsj.power.common.def.dto.job.SysRecordLogDTO;
import com.bsj.power.common.def.dto.job.WorkPersonnelDTO;
import com.bsj.power.common.def.entity.job.Job;
import com.bsj.power.common.def.entity.job.WorkPersonnel;
import com.bsj.power.common.def.entity.log.SysRecordLog;
import com.bsj.power.common.def.entity.log.SysRecordLogExportVO;
import com.bsj.power.common.def.enums.BusinessType;
import com.bsj.power.common.def.vo.JobRemindVO;
import com.bsj.power.common.def.vo.pls.AlarmReportVO;
import com.bsj.power.common.def.vo.web.job.JobPageVO;
import com.bsj.power.common.def.vo.web.job.JobVO;
import com.bsj.power.common.def.vo.web.job.media.BackTimeMediaVO;
import com.bsj.power.common.http.PersonHttp;
import com.bsj.power.common.util.DateUtils;
import com.bsj.power.job.service.JobService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.bsj.power.common.util.DateUtils.yearMonthDay;

/**
 * @author yinhao
 * @version 1.0
 * @description 作业工单管理器
 * @date 2024/6/11
 */
@RestController
@RequestMapping("/work")
public class WorkController {

    @Autowired
    private JobService jobService;

    @Autowired
    private RedisCached redisCached;

    @Autowired
    private PersonHttp personHttp;

    /**
     * 新增和修改工单信息
     *
     * @param dto
     * @return
     */
    @PostMapping("/doAddAndUpdateJob")
//    @SaCheckPermission("/job/work")
    public JsonResult<Long> doAddAndUpdateJob(@Validated @RequestBody JobDTO dto) {
        return JsonResult.success(jobService.addAndUpdateJob(dto));
    }

    /**
     * 分页查询工单信息
     *
     * @param dto
     * @return
     */
    @GetMapping("/doJobPageList")
//    @SaCheckPermission("/job/work")
    @Log(title = "工单模块", desc = "分页查询工单信息", businessType = BusinessType.SELECT)
    public JsonResult<List<JobVO>> doJobPageList(@Validated JobSearchDTO dto) {
        return jobService.jobPageList(dto);
    }

    /**
     * 根据工单分页获取报警列表
     *
     * @param dto
     * @return
     */
    @GetMapping("/doJobAlarmReport")
//    @SaCheckPermission("/job/work")
    @Log(title = "工单模块", desc = "根据工单分页获取报警列表", businessType = BusinessType.SELECT)
    public JsonResult<List<AlarmReportVO>> doJobAlarmReport(AlarmReportSearchDTO dto) {
        if (dto.getJobId() == null) {
            throw new ApiException(JsonResultEnum.PARAM_ERROR);
        }
        return jobService.jobAlarmReport(dto);
    }

    /**
     * 作业板块数据统计第一栏
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     */
//    @SaCheckPermission("/job/work")
    @GetMapping("/doJobDataPageOne")
//    @Log(title = "工单模块", desc = "今日作业完成率、区域作业统计、近7日作业完成率", businessType = BusinessType.SELECT)
    public JsonResult<JobPageVO> doJobDataPageOne(String startTime, String endTime) {
//        if (StringUtils.isAnyBlank(startTime,endTime)) {
//            throw new ApiException(JsonResultEnum.PARAM_ERROR);
//        }
        return jobService.doJobDataPageOne(startTime, endTime);
    }

    /**
     * 作业板块数据统计第二栏
     *
     * @param classify [0]: 0-作业效率排行版团队 1-个人
     *                 [1]: 0-故障排行榜设备 1-区域
     * @return
     */
//    @SaCheckPermission("/job/work")
    @GetMapping("/doJobDataPageTwo")
//    @Log(title = "工单模块", desc = "作业效率排行榜、故障排行榜、作业时长趋势", businessType = BusinessType.SELECT)
    public JsonResult<JobPageVO> doJobDataPageTwo(Integer[] classify, String startTime, String endTime) {
        if (classify == null) {
            throw new ApiException(JsonResultEnum.PARAM_IS_NOT_NULL);
        }
        if (classify.length < 2) {
            throw new ApiException(JsonResultEnum.PARAM_ERROR);
        }
        return jobService.doJobDataPageTwo(classify, startTime, endTime);
    }

    /**
     * 用户操作日志
     *
     * @param sysRecordLogDTO
     * @return
     */
    @PostMapping(value = "/logPage2")
//    @SaCheckPermission("/master/system/logPage")
    public JsonResult<List<SysRecordLog>> logPage2(@RequestBody @Validated SysRecordLogDTO sysRecordLogDTO) {
        return jobService.logPage2(sysRecordLogDTO);
    }

    /**
     * 系统日志导出
     *
     * @param sysRecordLogDTO
     * @author zy
     * @time 2024/6/24 14:50
     */
//    @SaCheckPermission("/job/work")
    @GetMapping(value = "/logPageExport")
    public void logPageExport(HttpServletResponse response, SysRecordLogDTO sysRecordLogDTO) throws IOException {
        List<SysRecordLog> sysRecordLogs = jobService.logPageExport(sysRecordLogDTO);
        List<SysRecordLogExportVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(sysRecordLogs)) {
            for (int i = 0; i < sysRecordLogs.size(); i++) {
                SysRecordLog sysRecordLog = sysRecordLogs.get(i);
                SysRecordLogExportVO vo = new SysRecordLogExportVO();
                vo.setSerialNum(i + 1);
                BeanUtils.copyProperties(sysRecordLog, vo);
                Integer businessType = sysRecordLog.getBusinessType();
                String businessTypeName;
                switch (businessType) {
                    case 0:
                        businessTypeName = "其他";
                        break;
                    case 1:
                        businessTypeName = "新增";
                        break;
                    case 2:
                        businessTypeName = "查询";
                        break;
                    case 3:
                        businessTypeName = "删除";
                        break;
                    case 4:
                        businessTypeName = "修改";
                        break;
                    case 5:
                        businessTypeName = "导出";
                        break;
                    case 6:
                        businessTypeName = "导入";
                        break;
                    case 7:
                        businessTypeName = "登录";
                        break;
                    case 8:
                        businessTypeName = "退出登录";
                        break;
                    case 9:
                        businessTypeName = "下载";
                        break;
                    case 10:
                        businessTypeName = "接口异常";
                        break;
                    case 11:
                        businessTypeName = "视频查看";
                        break;
                    case 12:
                        businessTypeName = "异常通知";
                        break;
                    case 13:
                        businessTypeName = "回放下载";
                        break;
                    case 14:
                        businessTypeName = "云台控制";
                        break;
                    default:
                        businessTypeName = "其他";
                        break;
                }
                vo.setBusinessTypeName(businessTypeName);
                vos.add(vo);
            }
        }

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //编码 防止中文乱码
        String fileName = URLEncoder.encode("操作日志" + DateUtils.dateToStr(DateUtils.TIME_STANDARD_FORMAT2, new Date()), "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        EasyExcelFactory.write(response.getOutputStream(), SysRecordLogExportVO.class).sheet("操作日志")
                .doWrite(vos);
    }


    /**
     * 测试
     *
     * @param
     * @return
     */
    @GetMapping("/test")
    public JsonResult test() {
        String dateKey = DateUtils.dateToStr(yearMonthDay, new Date());
        redisCached.del(RedisConstant.JOB_ORDER_EVERYDAY_KEY + dateKey);
        return JsonResult.success();
    }


    /**
     * 时间追溯获取多媒体数据
     *
     * @param jobId 工单ID
     * @return
     */
//    @SaCheckPermission("/job/work")
    @GetMapping("/doBackTime")
    public JsonResult<List<BackTimeMediaVO>> doBackTime(Long jobId) {
        if (jobId == null) {
            throw new ApiException(JsonResultEnum.PARAM_ERROR);
        }
        return JsonResult.success(jobService.backTime(jobId));
    }

    /**
     * 质量计划同步
     *
     * @return com.bsj.power.common.config.global.JsonResult
     * @author ljx
     * @time 2024/7/11 10:19
     */
    @GetMapping("/qualityPlanSync")
    public JsonResult qualityPlanSync() {
        return JsonResult.success(jobService.qualityPlanSync());
    }

    /**
     * 作业工单添加作业人员信息
     *
     * @param dto
     * @return
     */
//    @SaCheckPermission("/job/work")
    @PostMapping("/addAndUpdateWorkPersonnel")
    public JsonResult<Integer> doAddAndUpdateWorkPersonnel(@Validated @RequestBody WorkPersonnelDTO dto) {
        return JsonResult.success(jobService.addAndUpdateWorkPersonnel(dto));
    }

    /**
     * 获取作业人员信息集合
     *
     * @param pageDTO
     * @param name
     * @param groupId
     * @return
     */
//    @SaCheckPermission("/job/work")
    @GetMapping("/queryWorkPersonnelPages")
    public JsonResult<List<WorkPersonnel>> queryWorkPersonnelPages(PageDTO pageDTO, String name, Integer groupId) {
        return jobService.queryWorkPersonnelPages(pageDTO, name, groupId);
    }


    /**
     * 模糊查询工单信息
     *
     * @param value
     * @return
     */
//    @SaCheckPermission("/job/work")
    @GetMapping("/fuzzyQueryJobList")
    public JsonResult fuzzyQueryJobList(@RequestParam("value") String value) {
        List<Job> jobList = jobService.fuzzyQueryJobList(value);
        JsonResult jsonResult = JsonResult.success();
        jsonResult.setData(jobList);
        return jsonResult;
    }

    /**
     * 根据工单获取异常提醒信息
     *
     * @param jobId
     * @return
     */
    @GetMapping("/queryJobRemind/{jobId}")
    public JsonResult<JobRemindVO> queryJobRemind(@PathVariable("jobId") Long jobId) {
        return jobService.JobRemindVO(jobId);
    }

    /**
     * 删除作业人员与工单的绑定关系
     *
     * @param jobId
     * @param workPersonnelId
     * @return com.bsj.power.common.config.global.JsonResult
     * @author ljx
     * @time 2024/11/11 9:30
     */
    @GetMapping("/deleteJobAssociation")
    public JsonResult deleteJobAssociation(Long jobId, Integer workPersonnelId) {
        return jobService.deleteJobAssociation(jobId, workPersonnelId);
    }

    @SaIgnore
    @PostMapping("/test")
    public JsonResult test(@RequestBody Job job) {
        job.setProcedure(null);
        job.setRisk(null);
        job.setPrecautionaryMeasures(null);
        job.setEmpNo("W00000074");
        job.setAreaType(NumericalConstants.ONE);
        job.setTemporaryEmpNos(List.of("42354432", "sdj8934r"));
        String jsonString = JSON.toJSONString(job);
        System.out.println(jsonString);
//        redisCached.hset(RedisConstant.JOB_ROOM_NO_INFO_KEY + job.getRoomNo(), job.getJobId() + "", jsonString);
//        System.out.println("缓存信息：" + redisCached.hget(RedisConstant.JOB_ROOM_NO_INFO_KEY + job.getRoomNo(), job.getJobId() + ""));
        return JsonResult.success();
    }

    @SaIgnore
    @GetMapping("/test1")
    public JsonResult test1() {
        System.out.println("缓存信息：" + redisCached.hget(RedisConstant.JOB_ROOM_NO_INFO_KEY + 112112, 33996 + ""));
        return JsonResult.success();
    }

//    @SaIgnore
//    @GetMapping("/testGetExtEventPersonNo")
//    public JsonResult queryWorkPersonnelPages(String idCardNo) {
//        String extEventPersonNo = personHttp.getExtEventPersonNoByIdCardNo(idCardNo);
//        if (StringUtils.isNotBlank(extEventPersonNo)) {
//            return JsonResult.fail("人员编号返回结果为空");
//        } else {
//            return JsonResult.success(extEventPersonNo);
//        }
//    }

}
